<route lang="json5" type="page">
	{
	layout: 'default',
	style: {
	navigationBarTitleText: '',
	navigationStyle: 'custom',
	},
	}
</route>

<template>
	<PageLayout :navbarShow="false">
		<view class="wrap" :style="{
        '--nav-height': `${statusBarHeight + navHeight}px`,
        '--status-bar-height': `${statusBarHeight}px`,
      }">
			<wd-tabs :customClass="getClass()" v-model="tabActive" @click="changeTab">
				<template v-for="(item, index) in tabList" :key="index">
					<wd-tab :title="item.title" :name="item.key">
						<scroll-view scroll-y class="scroll-container" refresher-enabled="true" :refresher-triggered="refreshing"
							@refresherrefresh="onRefresh"  @touchstart="onTouchStart" @touchend="onTouchEnd">
							 <view v-if="tabActive === '1' && liveList.length==0" style="text-align:center;height:37vh;border:0px solid red;">
							 	<image src="/static/images/nodata.png" mode="aspectFit" style="width:360rpx;"></image>
							     <view style="margin-top:-100rpx;font-size:30rpx;">当前无数据</view>
							 </view>
							 <view v-if="tabActive === '2' && liveList1.length==0" style="text-align:center;height:37vh;border:0px solid red;">
							 	<image src="/static/images/nodata.png" mode="aspectFit" style="width:360rpx;"></image>
							     <view style="margin-top:-100rpx;font-size:30rpx;">当前无数据</view>
							 </view>

							<!-- 直播列表 -->
							<view v-if="tabActive === '1'" class="live-list-fullscreen">

								<!-- 左列 -->
								<view class="column">
									<view class="live-card" v-for="live in leftList" :key="live.id"
										@click="handleClick(live)">
										<!-- <image class="cover" :src="live.liveUrl" mode="aspectFill" /> -->
										<view class="live-cover-wrapper">
										  <image class="cover" :src="live.liveUrl" mode="aspectFill" />
										  <view class="text-overlay">
										    <text class="cover-text">{{live.mainId_dictText}}</text>
										  </view>
										</view>
										<view class="info">
											<text class="name">{{ live.title }}</text>
											<text class="status" :class="live.state === '3' ? 'replay' : 'live'">
												{{ liveState.get(live.state) }}
											</text>
										</view>
									</view>
								</view>

								<!-- 右列 -->
								<view class="column">
									<view class="live-card" v-for="live in rightList" :key="live.id"
										@click="handleClick(live)">
										<!-- <image class="cover" :src="live.liveUrl" mode="aspectFill" /> -->
										<view class="live-cover-wrapper">
										  <image class="cover" :src="live.liveUrl" mode="aspectFill" />
										  <view class="text-overlay">
										    <text class="cover-text">{{live.mainId_dictText}}</text>
										  </view>
										</view>
										<view class="info">
											<text class="name">{{ live.title }}</text>
											<text class="status" :class="live.state === '3' ? 'replay' : 'live'">
												{{ liveState.get(live.state) }}
											</text>
										</view>
									</view>
								</view>
							</view>
							<!-- 直播回放 -->
							<view v-if="tabActive === '2'" class="live-list-fullscreen">

								<view class="column">

									<view class="live-card" v-for="live in leftList1" :key="live.id"
										@click="handleClick(live)">
										<!-- <image class="cover" :src="live.liveUrl" mode="aspectFill" /> -->
										<view class="live-cover-wrapper">
										  <image class="cover" :src="live.liveUrl" mode="aspectFill" />
										  <view class="text-overlay">
										    <text class="cover-text">{{live.mainId_dictText}}</text>
										  </view>
										</view>
										<view class="info">
											<text class="name">{{ live.title }}</text>
											<text class="status" :class="live.state === '3' ? 'replay' : 'live'">
												{{ liveState.get(live.state) }}
											</text>
										</view>
									</view>
								</view>

								<!-- 右列 -->
								<view class="column">
									<view class="live-card" v-for="live in rightList1" :key="live.id"
										@click="handleClick(live)">
										<!-- <image class="cover" :src="live.liveUrl" mode="aspectFill" /> -->
										<view class="live-cover-wrapper">
										  <image class="cover" :src="live.liveUrl" mode="aspectFill" />
										  <view class="text-overlay">
										    <text class="cover-text">{{live.mainId_dictText}}</text>
										  </view>
										</view>
										<view class="info">
											<text class="name">{{ live.title }}</text>
											<text class="status" :class="live.state === '3' ? 'replay' : 'live'">
												{{ liveState.get(live.state) }}
											</text>
										</view>
									</view>
								</view>
							</view>
						</scroll-view>
					</wd-tab>
				</template>
			</wd-tabs>
		</view>
	</PageLayout>
</template>

<script lang="ts" setup>
	// import chatList from '../message/components/chatList.vue'
	// import addressBookList from '../message/components/addressBookList.vue'
	import { platform, isMp } from '@/utils/platform'
	import { http } from '@/utils/http'
	defineOptions({
		name: 'live',
		options: {
			// apply-shared‌：当前页面样式会影响到子组件样式.(小程序)
			// shared‌：当前页面样式影响到子组件，子组件样式也会影响到当前页面.(小程序)
			styleIsolation: '‌shared‌',
		},
	})
	import { ref, nextTick, computed } from 'vue'
	import { onLoad, onShow, onPullDownRefresh  } from '@dcloudio/uni-app'
	import { useUserStore } from '@/store/user'

	const globalData = getApp().globalData
	const { systemInfo, navHeight } = globalData
	const { statusBarHeight } = systemInfo
	console.log('systemInfo:::', systemInfo)
	const tabList = ref([
		{ key: '1', title: '我的直播' },
		{ key: '2', title: '观看直播' },
	])
	const tabActive = ref<string>('1')
	const getClass = () => {
		return `${platform} ${isMp ? 'mp' : ''}`
	}
	const liveState = new Map([
		["1", "未开始"],
		["2", "直播中"],
		["3", "已结束"]
	])

	// 重进页面刷新
	onShow(() => {
		console.log("onShow live/index")
		queryList()
	})

	// 下拉刷新
	const refreshing = ref(false)
	const onRefresh = () => {
	  refreshing.value = true
	  queryList()
	}

	const handleClick = (item) => {
		if (!item.id) return;
		if (item.mainId === currentUserId) {
			if (item.state == '3') {
				uni.showToast({
					title: "直播已结束",
					icon: "none"
				})
				return
			}
			// 跳转到主播页面
			uni.navigateTo({
				url: `/pages-live/live?roomId=${item.id}&userId=${currentUserId}`
			});
		} else {
			if (item.state == '3') {
				uni.showToast({
					title: "直播已结束",
					icon: "none"
				})
				return
			} else if (item.state == '1') {
				uni.showToast({
					title: "直播暂未开始",
					icon: "none"
				})
				return
			}
			// 跳转到观众观看页面
			uni.navigateTo({
				url: `/pages-live/watch?roomId=${item.id}&mainId=${item.mainId}&userId=${currentUserId}`
			});
		}
	}

	let liveList = ref([])
	let liveList1 = ref([])
	let leftList = ref([])
	let rightList = ref([])
	let leftList1 = ref([])
	let rightList1 = ref([])
	const queryList = () => {
		http
			.get('/api/live/listmy',{pageSize:50,mainId:currentUserId})
			.then((res : any) => {
				if (res.success) {
					for(var i=0;i<res.result.records.length;i++){
						if(!res.result.records[i].liveUrl){
							res.result.records[i].liveUrl="/static/images/zhibo.jpg"
						}else{
							res.result.records[i].liveUrl=getApp().globalData.imgUrl+res.result.records[i].liveUrl
						}
					}
					liveList.value = (res.result.records)
					// 拆成左右两列（奇偶分配）
					const left = [], right = []
					liveList.value.forEach((item, i) => {
						(i % 2 === 0 ? left : right).push(item)
					})
					leftList.value = left
					rightList.value = right
					// nextTick(() => {
					// 	setTimeout(() => {
					// 		sortByIzTop(liveList.value)
					// 		liveList.value = [...liveList.value]
					// 	}, 10)
					// })
					refreshing.value = false
				} else {
					console.log(res)
				}
			})
			.catch((res) => {
				console.log('>>>', res)
			})

			getOtherLive()
	}

	const getOtherLive=()=>{
		http
			.get('/api/live/listother',{pageSize:50,mainId:currentUserId})
			.then((res : any) => {
				console.log("other")
				console.log(res)
				if (res.success) {
					for(var i=0;i<res.result.records.length;i++){
						if(!res.result.records[i].liveUrl){
							res.result.records[i].liveUrl="/static/images/zhibo.jpg"
						}else{
							res.result.records[i].liveUrl=getApp().globalData.imgUrl+res.result.records[i].liveUrl
						}
					}
					liveList1.value = (res.result.records)
					// 拆成左右两列（奇偶分配）
					const left = [], right = []
					liveList1.value.forEach((item, i) => {
						(i % 2 === 0 ? left : right).push(item)
					})
					leftList1.value = left
					rightList1.value = right
					// nextTick(() => {
					// 	setTimeout(() => {
					// 		sortByIzTop(liveList.value)
					// 		liveList.value = [...liveList.value]
					// 	}, 10)
					// })
					refreshing.value = false
				} else {
					console.log(res)
				}
			})
			.catch((res) => {
				console.log('>>>', res)
			})
	}

	const userStore = useUserStore()
	globalData.userInfo=userStore.userInfo
	const currentUserId = userStore.userInfo.userid // 当前登录用户 useUserStore

	// 点击title切换
    const changeTab=(e)=>{
		console.log(e)
		tabActive.value=e.name
	}

	// 左右滑动
	let startX = 0
	function onTouchStart(e) {
	  startX = e.touches[0].clientX
	}

	function onTouchEnd(e) {
	  const endX = e.changedTouches[0].clientX
	  const deltaX = endX - startX

	  if (Math.abs(deltaX) < 50) return // 忽略轻微滑动

	  const index = tabList.value.findIndex(t => t.key === tabActive.value)

	  if (deltaX < 0 && index < tabList.value.length - 1) {
	    tabActive.value = tabList.value[index + 1].key
	  } else if (deltaX > 0 && index > 0) {
	    tabActive.value = tabList.value[index - 1].key
	  }
	}

	const historyList = [{
		roomId: 2001,
		userId: 'user_003',
		title: '小红的回放'
	}]
</script>

<style lang="scss" scoped>
	.scroll-container{
		padding: 8px 8px;
	}
	.wrap {
		height: 100%;
	}

	:deep(.wd-tabs) {
		height: 100%;
		display: flex;
		flex-direction: column;

		&.mp {
			.wd-tabs__nav-container {
				padding-right: 7%;
			}
		}

		.wd-tabs__nav {
			background: linear-gradient(45deg, #0081ff, #1cbbb4);
			height: var(--nav-height);
			padding-top: var(--status-bar-height);

			.wd-tabs__nav-item {
				color: #fff;
			}
		}

		.wd-tabs__container {
			flex: 1;
			width: 100%;
		}

		.wd-tabs__body {
			position: relative;
		}

		.wd-tabs__line {
			background-color: #fff;
		}
	}

	:deep(.wd-tab) {
		.wd-tab__body {
			position: absolute;
			height: 100%;
			width: 100%;
			top: 0;
			left: 0;
		}
	}

	.list {
		display: flex;
		align-items: center;
		padding: 10px 15px;
		border-bottom: 1px solid rgba(229, 229, 229, 0.5);

		.avatar {
			width: 45px;
			height: 45px;
			border-radius: 50%;
			color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 22px;
			margin-right: 10px;
			background-color: #617f89;
			flex: none;

			&.blue {
				background-color: #0081ff;
			}

			&.azure-green {
				background-color: #02bbd5;
			}

			&.orange {
				background-color: #f37b1d;
			}
		}

		.content {
			font-size: 15px;
		}

		.live-list-grid {
			display: flex;
			flex-wrap: wrap;
			gap: 16rpx;
			/* 卡片间距 */
			padding: 20rpx;
		}
        .live-card0 {
			width: calc(100% - 88rpx);
			/* 两列布局，考虑间隙 */
			background: #fff;
			text-align:center;
			display: flex;
			overflow: hidden;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

		}
		.live-card {
			width: calc(50% - 8rpx);
			/* 两列布局，考虑间隙 */
			background: #fff;
			border-radius: 12rpx;

			overflow: hidden;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
			margin-bottom: 16rpx;
		}

		.cover {
			width: 100%;
			height: 300rpx;
			/* 固定高度 */
			display: block;
		}

		.info {
			padding: 20rpx;
			display: flex;
			flex-direction: column;
			gap: 8rpx;
		}

		.name {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}

		.status {
			font-size: 24rpx;
			padding: 4rpx 12rpx;
			border-radius: 20rpx;
			align-self: flex-start;
		}

		.status.live {
			background: #ffebe6;
			color: #ff4444;
		}

		.status.replay {
			background: #e6f3ff;
			color: #1890ff;
		}
	}


	.live-list-fullscreen {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		gap: 10rpx;
	}

	.column {
		width: 49%;
		// border-radius: 10%;
	}

	.live-card {
		background-color: #fff;
		margin-bottom: 20rpx;
		border-radius: 12rpx;
		border:1px solid #e3ecfa;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}
	.live-cover-wrapper {
	  position: relative;
	  width: 100%;
	  height: 180rpx;
	}



	.text-overlay {
	  position: absolute;
	  bottom: 0rpx;
	  left: 10rpx;
	  background-color: rgba(0, 0, 0, 0.5);
	  padding: 3rpx 6rpx;
	  border-radius: 8rpx;
	}

	.cover-text {
	  color: white;
	  font-size: 24rpx;
	}

	.cover {
		width: 100%;
		height: 180rpx;
		background-color: #ccc;
	}

	.info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8rpx;
	}

	.name {
		font-size: 26rpx;
		font-weight: 500;
		color: #333;
		width: 65%;
		overflow: hidden;
		white-space: nowrap; /* 禁止文本换行 */
		text-overflow: ellipsis; /* 超出部分显示为省略号 */
	}

	.status {
		font-size: 22rpx;
		padding: 2rpx 10rpx;
		border-radius: 8rpx;
	}

	.status.live {
		background-color: #ff4d4f;
		color: #fff;
	}

	.status.replay {
		background-color: #999;
		color: #fff;
	}

	.history-list {
		padding: 20rpx;
	}

	.history-item {
		margin-bottom: 20rpx;
		font-size: 28rpx;
	}
</style>
